var mongoose = require('../util/db');

var LabelSchema = mongoose.Schema({
    text: String,
    articleIds: [] //id of articles with the label
});

var Label = mongoose.model('Label', LabelSchema);

exports.save = function (text,articleId,fn) {
    Label.findOne(
        {text:text},
        function(err,data){
            if(err){
                fn(err);
            }else if(data){
                data.articleIds.push(articleId);
                Label.update({
                    _id:data.id
                },{
                    articleIds:data.articleIds
                },function(err){
                    fn(err);
                });
            }else{
                data=new Label({
                    text:text,
                    articleIds:[articleId]
                });

                data.save(function(err){
                    fn(err);
                });
            }
        });
}

exports.get = function (id, fn) {
    Label.findById(id, function (err, article) {
        fn(err, article);
    });
}

exports.list = function (fn) {
    Label.find(function (err, articles) {
        fn(err, articles);
    });
}